package de.tum.activities.StatsApp;

import java.util.ArrayList;
import java.util.List;

import org.achartengine.GraphicalView;
import org.xmlrpc.android.XMLRPCException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import de.tum.ExamApp.R;
import de.tum.Misc.Functions;
import de.tum.activities.ExamApp.ExamAppActivity;
import de.tum.activities.ExamEvaluation.ExamEvaluationActivity;
import de.tum.activities.Login.LoginActivity;
import de.tum.control.Synchronizer;
import de.tum.datatypes.Exam;
import de.tum.datatypes.ExamStatistics;

public class StatsActivity extends Activity implements OnClickListener{
	
	/**
	 * ViewFlipper holding all Views.
	 */
	private ViewFlipper switcher;
	
	private ProgressDialog progressDialog;
	
	
//	/**
//	 * Gesture Filter to detect the swips
//	 */
//	private GestureFilter detector;
//	
	/**
	 * For the swipping we are holding three views
	 */
	private List<View> views;
	
	
	int examId;
	
	String examName;
	
	
	int nbrOfParticipants = -1;
    int nbrOfFailed = -1;
    int nbrOfPassed = -1;
    double averageGrade = -1;
    double averageGradeW0Failed = -1;
    int maxPoints = -1;
    int[] gradingDistributionArray = new int[0];
	List<Double> achievedPoints = new ArrayList<Double>();
    double[] maxPointsPerExercise = new double[0];
    double[] averagePointsPerExercise = new double[0];
    double averagePoints = 0;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.switcher);

    	progressDialog = ProgressDialog.show(StatsActivity.this, "Evaluation", "Scanning ...");
        
        Bundle extras = getIntent().getExtras();     
        examId = extras.getInt("examID");
        examName = extras.getString("examName");
        
//        v0 = new AChartExample().execute(this);
//        
//        TextView stats_headline = (TextView) findViewById(R.id.stats_headline);
//        stats_headline.setText("Notenverteilung");
//        
//        LinearLayout chartLinearLayout = (LinearLayout) findViewById(R.id.stats_chart);
//        chartLinearLayout.addView(v0, new LayoutParams
//        		(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
//        
        
//        // Initialization of the GestureFilter
//        detector = new GestureFilter(this, this);
        
        //bind all resources
    	switcher = (ViewFlipper) findViewById(R.id.switcherView);

    	views = new ArrayList<View>();
    	
        loadGraphsAndHeadlinesIntoView();
        
    	
        
        
    }

    
    
    private void loadGraphsAndHeadlinesIntoView() {
    	
		
    	final Handler handler = new Handler(){

	      @Override
	      public void handleMessage(Message msg) {
	    	 Log.d("Message", "message text = "+msg.toString());
	    	 
	    	 progressDialog.dismiss();

	      	loadView();
	      	
	      	for(int i=0; i<views.size(); i++){
	    		switcher.addView(views.get(i));
	    	}
	        switcher.setDisplayedChild(0);
	    	 
	      }
	
    	};
    	
    	getExamStatistics();
		handler.sendEmptyMessage(0);
    	
    }
    	
    
    private void getExamStatistics() {
    	
		Synchronizer sync = new Synchronizer();
	    
		try {
			nbrOfParticipants = sync.getNumberOfParticipants(examId);
			nbrOfFailed = sync.getNumberOfFailed(examId);
		    nbrOfPassed = sync.getNumberOfPassed(examId);
		    averageGrade = sync.getAverageGrade(examId);
		    averageGradeW0Failed = sync.getAverageGradeOfPassed(examId);
		    achievedPoints = sync.getListOfAchievedPointsFirstCorrection(examId);
		    maxPoints = sync.getMaxPointsInExam(examId);
		    gradingDistributionArray = sync.getGradingDistributionArray(examId);
		    maxPointsPerExercise = sync.getMaxPointsPerExercise(examId);
		    averagePointsPerExercise = sync.getAveragePointsPerExercise(examId);
		} catch (XMLRPCException e) {
			e.printStackTrace();
		}
    	Log.d("Statistics","number of participants: "+nbrOfParticipants);
    	
    	averageGrade = (int) (averageGrade*100) / (double) (100);
    	averageGradeW0Failed = (int) (averageGradeW0Failed*100) / (double) (100);
    	
    	
    	for(int i=0; i<achievedPoints.size(); i++){
    		averagePoints = averagePoints + achievedPoints.get(i);
    	}
    	
    	averagePoints = averagePoints / achievedPoints.size();
    	averagePoints = (int) (averagePoints*100) / (double) (100);
    	
	}

	private void loadView() {
		
		View addView;
	
		LayoutInflater inflater = (LayoutInflater) this.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		GraphicalView chart;
		TextView stats_headline;
		LinearLayout chartLinearLayout;
		Button nextButton, prevButton;
		
		
		
		/**
		 * FIRST VIEW
		 */
		
		
		addView = inflater.inflate(R.layout.statsapp_general,null);
		   
		stats_headline = (TextView) addView.findViewById(R.id.stats_headline);
		stats_headline.setText("General Information");
		   
		TextView nbrOfParticipantTextView = (TextView) addView.findViewById(R.id.stats_number_of_participants_textView);
		nbrOfParticipantTextView.setText(""+nbrOfParticipants);
		
		TextView nbrOfPassedTextView = (TextView) addView.findViewById(R.id.stats_passed_textView);
		nbrOfPassedTextView.setText(""+nbrOfPassed);
		
		TextView nbrOfFailedTextView = (TextView) addView.findViewById(R.id.stats_failed_exams_textView);
		nbrOfFailedTextView.setText(""+nbrOfFailed);
		
		TextView averageTextView = (TextView) addView.findViewById(R.id.stats_average_textView);
		averageTextView.setText(""+averageGrade);
		
		TextView averageWoStatsTextView = (TextView) addView.findViewById(R.id.stats_average_without_textView);
		averageWoStatsTextView.setText(""+averageGradeW0Failed);
		
		TextView averagePointsTextView = (TextView) addView.findViewById(R.id.stats_average_points);
		averagePointsTextView.setText(""+averagePoints);
		
		nextButton = (Button) addView.findViewById(R.id.stats_nextButton);
		prevButton = (Button)  addView.findViewById(R.id.stats_prevButton);
		
		nextButton.setOnClickListener(this);
		prevButton.setOnClickListener(this);
		
		views.add(addView);
		/**
		 * SECOND VIEW
		 */
		
		addView = inflater.inflate(R.layout.statsapp,null);
		chart  = new GradingDistributionPieChart().execute(this, gradingDistributionArray);
		   
		stats_headline = (TextView) addView.findViewById(R.id.stats_headline);
		stats_headline.setText("Notenverteilung - Pie diagram");
		   
		chartLinearLayout = (LinearLayout) addView.findViewById(R.id.stats_chart);
		chartLinearLayout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		nextButton = (Button) addView.findViewById(R.id.stats_nextButton);
		prevButton = (Button)  addView.findViewById(R.id.stats_prevButton);
		
		nextButton.setOnClickListener(this);
		prevButton.setOnClickListener(this);
		
		views.add(addView);
		
		/**
		 * THIRD VIEW
		 */
		addView = inflater.inflate(R.layout.statsapp,null);
		chart = new GradeDistributionBarChart().execute(this, gradingDistributionArray);	
		
		stats_headline = (TextView) addView.findViewById(R.id.stats_headline);
		stats_headline.setText("Notenverteilung - Bar diagram");
		   
		chartLinearLayout = (LinearLayout) addView.findViewById(R.id.stats_chart);
		chartLinearLayout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		nextButton = (Button) addView.findViewById(R.id.stats_nextButton);
		prevButton = (Button)  addView.findViewById(R.id.stats_prevButton);
		
		nextButton.setOnClickListener(this);
		prevButton.setOnClickListener(this);
		
		views.add(addView);
		
		/**
		 * FORTH VIEW
		 */
		double[] achievedPointsArray = new double[achievedPoints.size()];
		
		for(int i=0; i< achievedPointsArray.length; i++){
			achievedPointsArray[i] = achievedPoints.get(i);
		}
		
		addView = inflater.inflate(R.layout.statsapp,null);
		chart = new AchievedPointsBarChart().execute(this, achievedPointsArray, maxPoints);	
		
		stats_headline = (TextView) addView.findViewById(R.id.stats_headline);
		stats_headline.setText("Notenverteilung - Bar diagram");
		   
		chartLinearLayout = (LinearLayout) addView.findViewById(R.id.stats_chart);
		chartLinearLayout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		nextButton = (Button) addView.findViewById(R.id.stats_nextButton);
		prevButton = (Button)  addView.findViewById(R.id.stats_prevButton);
		
		nextButton.setOnClickListener(this);
		prevButton.setOnClickListener(this);
		
		views.add(addView);
		
		/**
		 * FIFTH VIEW
		 */
		
		addView = inflater.inflate(R.layout.statsapp,null);
		chart = new AveragePointsPerExerciseBarChart().execute(this, maxPointsPerExercise, averagePointsPerExercise);	
		
		stats_headline = (TextView) addView.findViewById(R.id.stats_headline);
		stats_headline.setText("Notenverteilung - Bar diagram");
		   
		chartLinearLayout = (LinearLayout) addView.findViewById(R.id.stats_chart);
		chartLinearLayout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		nextButton = (Button) addView.findViewById(R.id.stats_nextButton);
		prevButton = (Button)  addView.findViewById(R.id.stats_prevButton);
		
		nextButton.setOnClickListener(this);
		prevButton.setOnClickListener(this);
		
		views.add(addView);
		
	}



	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id== R.id.stats_prevButton){
			switcher.setInAnimation(Functions.inFromRightAnimation());
			switcher.setOutAnimation(Functions.outToLeftAnimation());
			switcher.showNext();
		}else if(id == R.id.stats_nextButton){
			switcher.setInAnimation(Functions.inFromLeftAnimation());
			switcher.setOutAnimation(Functions.outToRightAnimation());
			switcher.showPrevious();
		}else{
			
		}
	}
	
	
	



//	public void onSwipe(int direction) {
//		switch (direction) {
//		case GestureFilter.SWIPE_LEFT:
//			switcher.setInAnimation(Functions.inFromRightAnimation());
//            switcher.setOutAnimation(Functions.outToLeftAnimation());
//			switcher.showNext();
//			Log.d("GestureListener", "Left!");
//			break;
//		case GestureFilter.SWIPE_RIGHT:
//			switcher.setInAnimation(Functions.inFromLeftAnimation());
//			switcher.setOutAnimation(Functions.outToRightAnimation());
//			switcher.showPrevious();
//			Log.d("GestureListener", "Right!");
//			break;
//		default:
//			Log.d("GestureListener", "OTHER!");
//			break;
//		}
//		
//	}
//
//    /**
//     * Redirects all TouchEvents to the GestureFilter.
//     */
//	public boolean dispatchTouchEvent(MotionEvent me){ 
//
//  	  this.detector.onTouchEvent(me);
//  	  return super.dispatchTouchEvent(me); 
//  	}


	  

}
